//图片方向处理,安卓微信压缩问题hack,IOS6/7压缩扭曲,多张上传
var arr=[]; //图片路径
var j = 1;  //base64转码
//图片上传
var u = navigator.userAgent, app = navigator.appVersion;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
//alert('是否是Android：'+isAndroid);
//alert('是否是iOS：'+isiOS);
if(isAndroid) {
    $("#multiple").attr('capture', 'camera');
}

$("#multiple").on('change', function (e) {
    var i = 0,
        notSupport = false;

    var files = e.target.files,
        len = files.length,
        name = "";

    // 循环多张图片，需要for循环和notSupport变量支持（检测）
    for (; i < len; i++) {
        if (files[i]) {
            if(!/image\/\w+/.test(files[i].type)){
                mui.toast("请确保文件为图像类型");
                return false;
            }

            if (!notSupport) {
                (function(i) {
                    //图片方向处理,安卓微信压缩问题hack,IOS6/7压缩扭曲
                    new html5ImgCompress(files[i], {
                        before: function(file) {
                            //console.log('多张: ' + i + ' 压缩前...');
                        },
                        done: function (file, base64) { // 这里是异步回调，done中i的顺序不能保证
                            //console.log('多张: ' + i + ' 压缩成功...');
                            //insertImg(file, j); //处理前
                            name = files[i].name;
                            insertImg(base64, j++, name);
                        },
                        fail: function(file) {
                            //console.log('多张: ' + i + ' 压缩失败...');
                        },
                        complate: function(file) {
                            //console.log('多张: ' + i + ' 压缩完成...');
                        },
                        notSupport: function(file) {
                            notSupport = true;
                            alert('浏览器不支持！');
                        }
                    });
                })(i);
            }
        }
    }
    //console.log(arr);
});

//插入图片
function insertImg(file, j, name) {
    var img = new Image(),
        title, src, size, base;

    if (typeof file === 'object') {
        title = '前';
        size = file.size;
        src = URL.createObjectURL(file);
        base = 1024;
    } else {
        title = '后';
        size = file.length;
        src = file;
        base = 1333;
    }

    //src = file;
    var li=$('<li class="mui-table-view-cell mui-media mui-col-xs-6"></li>');
    img.onload = function() {
        $("<img class='mui-media-object' src="+src+" name="+name+" data-preview-src='' data-preview-group='1'/><div class='mui-media-body' onclick=$(this).prev().parent().remove();delectImg('"+src+"');>删除</div>").appendTo(li);
        console.log('图片' + j + '，名字' + name +'，处理' + title + '质量约：' + (size / base).toFixed(2) + 'KB' + '，尺寸：' + this.width + '*' + this.height);
    };
    $("#imgList").append(li);
    img.src = src;
    arr.push(src);
    file = null; // 处理完清缓存
};



//图片预览
mui.previewImage();

var tbproject_value =[],
    tbproject_code_all = [],
    tbcompany_value = [],
    tbcompany_code =[],
    otherCompany_value = "",
    isotherCompany = false,
    ifAbatement = ""; //不计免赔

$(function(){
    //表单验证正则
    var usernamereg = /^[\u4e00-\u9fa5]{1,5}$/,
        idCardreg = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,
        phoneNoreg = /^0?(1)(?!\\1{10}$)[0-9]{10}$/,
        addressreg = /^[a-zA-Z0-9\u4e00-\u9fa5]{1,100}$/,
        carnumberreg = /^[A-Z]{1}[A-Z0-9]{5,6}$/,
        companynamereg = /^[a-zA-Z0-9_\u4e00-\u9fa5\(|\)|\（|\）|\-|\ |]{4,100}$/i,  //允许输入字符："abc123汉字_-()（）空格";
        businesscardreg = /^\d{15}$/;

    function isValid() {
        $("#username").bind('input porpertychange',function(){
            formValid("#username",usernamereg,"车主姓名","小于等于5个汉字",false);
        });
        $("#idCard").bind('input porpertychange',function(){
            formValid("#idCard",idCardreg,"车主身份证号","输入的车主身份证号不正确",true);
        });
        $("#phoneNo").bind('input porpertychange',function(){
            formValid("#phoneNo",phoneNoreg,"车主手机号","您输入的手机号码格式不正确",false);
        });
        $("#address").bind('input porpertychange',function(){
            formValid("#address",addressreg,"保单邮寄地址","您输入的保单邮寄地址不正确",false);
        });
        $("#carnumber").bind('input porpertychange',function(){
            formValid("#carnumber",carnumberreg,"车牌号码","您输入的车牌号码不正确",true);
        });
        $("#companyname").bind('input porpertychange',function(){
            formValid("#companyname",companynamereg,"企业名称","您输入的企业名称不正确",false);
        });
        $("#businesscard").bind('input porpertychange',function(){
            formValid("#businesscard",businesscardreg,"营业证登记号","您输入的营业证登记号不正确",false);
        });
    }
    isValid();

    //其他投保公司    
    $("#otherCompany").bind('input porpertychange',function(){
        var otherVal = $.trim($(this).val());
        if(otherVal.length >= 0){
            $('input[name="companycb"]').each(function(){
                $(this).attr("disabled","disabled");
                $(this).parent(".mui-radio").addClass("mui-disabled");
            });
            otherCompany_value = otherVal;
            isotherCompany = true;
        }
        if(otherVal.length == 0){
            $('input[name="companycb"]').each(function(){
                $(this).removeAttr("disabled");
                $(this).parent(".mui-radio").removeClass("mui-disabled");
            });
            otherCompany_value = "";
            isotherCompany = false;
        }
    });
    document.getElementById("otherCompany").nextSibling.addEventListener('tap',function(){
        $('input[name="companycb"]').each(function(){
            $(this).removeAttr("disabled");
            $(this).parent(".mui-radio").removeClass("mui-disabled");
        });
        otherCompany_value = "";
        isotherCompany = false;
    });

    //被保险人类型
    var applyType = "GR";
    mui('#segmentedControl').on('tap','a',function(){
        applyType = $(this).attr("value");
        if(applyType == "GR"){ //个人
            $("#item1").show();
            $("#item2").hide();
            $("#tip").text("请上传身份证正反面和机动车行驶证");
            $("div[id $='-description']").each(function() {
                $(this).removeClass("field-invalidmsg").text("");
            });
        }else if(applyType == "QY"){
            $("#item1").hide();
            $("#item2").show();
            $("#tip").text("请上传营业执照和机动车行驶证");
            $("div[id $='-description']").each(function() {
                $(this).removeClass("field-invalidmsg").text("");
            });
        }
    });

    //是否新车
    var newCar = 1; //不是新车
    $("#ifNewCar").click(function(){
        newCar = this.classList.contains('mui-active');
        if(newCar){
            $("#notNewCar").hide();
            $("#carnumber-description").text("");
            newCar = 0; //新车
        }else {
            $("#notNewCar").show();
            nullValid("#carnumber","车牌号码");
            newCar = 1;
        }
    });


    //投保项目
    $("#tbprojectpop").find(".mui-input-row").each(function () {
        $(this).click(function () {
            var inputCheck = $(this).find("input[name=projectcb]"),
                notCheck = $(this).find("input[name=notcb]");
            if(inputCheck.is(':checked')){
                $(this).find(".tb").show(); //显示投保
                $(this).find(".mui-checkbox").eq(1).removeClass("mui-disabled"); //显示不计免赔
                notCheck.removeAttr("disabled"); //不计免赔可用
            }else{
                $(this).find(".tb").hide();
                $(this).find(".mui-checkbox").eq(1).addClass("mui-disabled");
                notCheck.prop({
                    "disabled":"disabled",
                    "checked":"checked"
                });
            }
        })
    })

    //表单申请按钮提交
    mui(document.body).on('tap', '#ipApplyBtn', function(e) {
        //表单为空验证
        var i = 0;
        if(applyType == "GR"){ //个人
            i+= nullValid("#username","车主姓名");
            i+= nullValid("#idCard","身份证");
        }else{
            i+= nullValid("#companyname","企业名称");
            i+= nullValid("#businesscard","营业证登记号");
        }
        i+= nullValid("#phoneNo","车主手机号");
        i+= nullValid("#address","保单邮寄地址");
        if(newCar != 0){ //不是新车
            i+= nullValid("#carnumber","车牌号码");
        }

        //点击申请按钮后，调用实时验证
        //isValid();

        //表单验证未通过
        if(i > 0) {
            $("html,body").animate({scrollTop:0}, 500);
            mui.toast("请输入正确的信息");
            return false;
        }

        //上传图片为空验证
        if(arr.length==0){
            mui.toast("请选择上传图片");
            return false;
        }

        //投保项目为空验证
        if(tbproject_value.length==0){
            mui.toast("请选择投保项目");
            return false;
        }
        //投保公司为空验证
        if(tbcompany_value.length==0){
            mui.toast("请选择投保公司");
            return false;
        }

        var insurProduct = {
            "consumerType":applyType,
            "contractCity":$("#contractCity").val(),
            "consumerPhone":$("#phoneNo").val(),
            "receiveAddress":$("#address").val(),
            "ifNewCar":newCar,
            "plateNumber":$("#carnumber").val(),
            "companyName":$("#tbcompany").attr("name"),
            "companyCode":$("#tbcompany").attr("code"),
            "remark":$("#note").val()
        };
        if(applyType == "GR"){
            insurProduct.consumerName = $("#username").val(),
            insurProduct.consumerIdCard = $("#idCard").val()
        }else if(applyType == "QY"){
            insurProduct.enterpriseName = $("#companyname").val(),
            insurProduct.enterpriseLicence = $("#businesscard").val()
        }
        console.log(insurProduct);

        mui(this).button('loading');

        //其他数据
        $.ajax({
            type:"POST",
            url: url + 'weixinOrder/orderApplySubmit',
            dataType:"json",
            data:{
                "openId":openId,
                "insurProductList":JSON.stringify(tbproject_code_all),
                "insurOrderDO":JSON.stringify(insurProduct)
            },
            cache:false,
            success:function(data){
                console.log(data.data);
                if(data.repCode = "000000"){
                    var applyName = "";
                    if(data.data.consumerType == "GR"){
                        applyName = data.data.consumerName;
                    }else{
                        applyName = data.data.enterpriseName;
                    }

                    //图片上传
                    var formdata = new FormData();
                    var imgs = $("#imgList").find("li").find("img");
                    for (var i = 0;i < imgs.length;i++){
                       formdata.append("uploadFileList",dataURItoBlob(imgs[i].src));
                       formdata.append("fileName",imgs[i].name);
                    }
                    formdata.append("bussinessType","SQ");
                    formdata.append("orderCode",data.data.orderCode);

                    mui.toast("正在上传"+arr.length+"张图片，请稍等...");
                    //附件上传
                    $.ajax({
                       url: url + 'weixinFile/upload',
                       type: "POST",
                       processData: false,
                       contentType: false,
                       data: formdata,
                       success: function(data){
                           console.log(data);
                           if(data.repCode = "000000"){
                                mui.toast("提交成功！");
                               var setUrl = "ip_apply_success.html?applyName=\"" +applyName+ "\"&openId=" + openId;
                               setTimeout("window.location.href='"+setUrl+"'", 1000);

                           }
                       },
                       error:function(){
                           mui('#ipApplyBtn').button('reset');
                           mui.toast("附件上传失败");
                       }
                    });
                }else if(data.repCode == "999999") {
                    mui('#ipApplyBtn').button('reset');
                    mui.toast("认证失败");
                }
            },
            error:function(){
                mui('#ipApplyBtn').button('reset');
                mui.toast("error");
            }
        });

        e.stopPropagation();
    });

})

//表单为空验证（#对象,为空提示）
function nullValid(obj,nullTip){
    if ($(obj).val()==undefined || $(obj).val()=="" || $(obj).val()==null) {
        $(obj + "-description").addClass("field-invalidmsg").text(nullTip +"不允许为空");
        return 1;
    }else{
        $(obj + "-description").removeClass("field-invalidmsg").text("");
        return 0;
    }
}

//表单实时监听验证（#对象,正则,为空提示,错误提示,是否大写）
function formValid(obj,reg,nullTip,errorTip,toUpperCase){
    if ($(obj).val()==undefined || $(obj).val()=="" || $(obj).val()==null) {
        $(obj + "-description").addClass("field-invalidmsg").text(nullTip +"不允许为空");
        return false;
    } else if(!toUpperCase){
        if(!reg.test($(obj).val())){
            $(obj + "-description").addClass("field-invalidmsg").text(errorTip);
            return false;
        }else{
            $(obj + "-description").removeClass("field-invalidmsg").text("");
        }
    } else{
        if(!reg.test(($(obj).val()).toUpperCase())){
            $(obj + "-description").addClass("field-invalidmsg").text(errorTip);
            return false;
        }else{
            $(obj + "-description").removeClass("field-invalidmsg").text("");
        }
    }
}

//显示关闭弹出菜单
function blockScroll(father,scrollwrapper,closebtn,num){
    $(father).css("display","-webkit-box");
    myScroll1 = new IScroll(scrollwrapper, {
        scrollbarClass: 'myScrollbar' ,
        hScrollbar:false,
        vScroll:true,
        hideScrollbar: true //是否隐藏滚动条
    });
    $("body").bind("touchmove",function(e){
        e.preventDefault();
    });

    $(closebtn).unbind("click").bind("click",function(){
        $(father).css("display","none");
        $("body").unbind("touchmove");
        if(num == '0'){
            tbprojectBtn();
        }else{
            tbcompany();
        }
    });
}

//投保项目提交
function tbprojectBtn() {
    var tbproject = $("#tbproject");
    tbproject.text("请选择投保项目");
    tbproject_value = [];
    tbproject_code_all = [];

    $('input[name="projectcb"]:checked').each(function(){
        tbproject_value.push($(this).val());
        var tbproject_code = {};
        tbproject_code.productName = $(this).val();
        tbproject_code.productCode = $(this).attr("code");
        //不计免赔
        var notCheck = $(this).parent().next().find("input[name=notcb]");
        if(notCheck.is(':checked')){ //选中不计免赔
            ifAbatement = 0;
        }else{
            ifAbatement = 1;
        }
        tbproject_code.ifAbatement = ifAbatement;
        //选择框值
        var insurePrice = $(this).parent().next().next().find("select").val();
        tbproject_code.insurePrice = insurePrice;
        tbproject_code_all.push(tbproject_code);
    });

    console.log(tbproject_code_all);

    if(tbproject_value.length==0){
        mui.toast("请选择投保项目");
        //return false;
    }else{
        tbproject.text("");
        for(var i = 0;i < tbproject_value.length; i++) {
            if(i<(tbproject_value.length-1)){
                tbproject.removeClass("update").append(tbproject_value[i]+"，");
            }else{
                tbproject.removeClass("update").append(tbproject_value[i]);
            }
        }
    }

}

//投保公司提交
function tbcompany(){
    var tbcompany = $("#tbcompany");
    if($.trim($("#note").val())!=0){
        tbcompany.attr("note", $.trim($("#note").val()));
    }    
    tbcompany.text("请选择投保公司").addClass("update");
    tbcompany_value = [];
    tbcompany_code = [];

    if(!isotherCompany){
        var isNullRadio = $('input[name="companycb"]:checked');
        if(isNullRadio.val() == "" || isNullRadio.val() == null || isNullRadio.val() == undefined){
            //console.log(isNullRadio.val());
        }else{
            tbcompany_value.push(isNullRadio.val());
            tbcompany_code.push(isNullRadio.attr("code"));
        }
    }else{ //其他投保公司
        console.log("其他投保公司");
        tbcompany_value.push(otherCompany_value);
        tbcompany_code.push("QT");
    }

    if(tbcompany_value.length == 0){
        mui.toast("请选择投保公司");
        return false;
    }else{
        $("#tbcompany").removeClass("update").html(tbcompany_value[0]).attr({"code":tbcompany_code[0],"name":tbcompany_value[0]});
    }
}

